package com.xiaoxin.experience.system.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

/**
 * @author xiaoxin
 */
@Slf4j
@Configuration
public class CustomizeDataSourceInitializer
{

    @Bean
    public DataSource dataSource()
    {
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(DataConfig.CONNECTION_DRIVER_CLASS_NAME);
        ds.setUrl(DataConfig.CONNECTION_URL);
        ds.setUsername(DataConfig.CONNECTION_USERNAME);
        ds.setPassword(DataConfig.CONNECTION_PASSWORD);
        return ds;
    }

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource)
    {
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator()
    {
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        try
        {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath:sql/*.sql");
            for (Resource resource : resources)
            {
                populator.addScript(resource);
            }
        }
        catch (Exception e)
        {
            log.error("sql init error: ", e);
        }
        return populator;
    }
}
